﻿using KseCms.Core;

namespace KseCms.Application
{
    public class ProductService : IProductService, ITransient
    {
        private readonly IRepository<Product> _productRepository;

        public ProductService(IRepository<Product> productRepository)
        {
            _productRepository = productRepository;
        }

        public async Task<ProductDto> GetById(string id)
        {
            var productEntity = await _productRepository.DetachedEntities.FirstOrDefaultAsync(n=>n.Id==id);

            return productEntity.Adapt<ProductDto>();
        }

        public async Task<PagedList<ProductDto>> GetList(PageDto page)
        {
            var productEntities = await _productRepository.AsQueryable(false).ToPagedListAsync(page.PageIndex,page.PageSize);

            return productEntities.Adapt<PagedList<ProductDto>>();
        }

        public async Task Create(ProductDto product)
        {
            var productEntity = product.Adapt<Product>();

            await _productRepository.InsertNowAsync(productEntity);
        }

        public async Task Delete(string id)
        {
            if (!IsExists(id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            await _productRepository.DeleteNowAsync(id);
        }

        public async Task Update(ProductDto product)
        {
            UpdateValidation(product);

            var productEntity = product.Adapt<Product>();

            await _productRepository.UpdateNowAsync(productEntity);
        }

        private void UpdateValidation(ProductDto product)
        {
            if (!IsExists(product.Id))
                throw Oops.Oh(ErrorCodes.record_not_exist);

            //to-do other validate
        }

        private bool IsExists(string id)
        {
            return _productRepository.DetachedEntities.Any(u => u.Id == id);
        }
    }
}